<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
      <el-form-item label="日期" prop="createdAt">
      <template #label>
        <span>
          日期
          <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
      </template>
      <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
       —
      <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
      </el-form-item>


      <el-form-item label="平台类型：" prop="platId">
            <el-select v-model="searchInfo.platId" clearable placeholder="请选择" @clear="()=>{searchInfo.platId=0}">
              <el-option v-for="(item,key) in platOptions" :key="key" :label="item.label" :value="item.value" />
            </el-select>
            </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <!-- <el-button icon="refresh" @click="onReset">重置</el-button> -->
          <el-button type="success" @click="allExport" v-show="true" >导出表格</el-button>

        </el-form-item>
      </el-form>
    </div>
    <div class="gva-card-box">
      <div class="gva-card">

        <div class="p-4">
          <el-row :gutter="10">
            <el-col
              :xs="24"
              :sm="12"
            >
            <div class="dashboard-line-box">
                      <div
              ref="echart"
              class="dashboard-line"
              />
            </div>
            
            </el-col>
            <el-col
              :xs="24"
              :sm="12"
            >
            <div class="dashboard-line-box">
                      <div
              ref="echartRate"
              class="dashboard-line"
              />
            </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>

    <div class="gva-table-box">

        <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="createTime"
        height="500"
        >
        <el-table-column align="left" label="日期" prop="createTime" width="180" />

        <el-table-column align="left" label="总新增" prop="regUser" width="120" />
        <el-table-column align="left" label="投放新增" prop="regUserByReferral" width="120" />
        <el-table-column align="left" label="活跃" prop="regUserByActive" width="120" />
        <el-table-column align="left" label="投放消耗" prop="statCost" width="120" />
        <el-table-column align="left" label="roi" prop="roi" width="80">
            <template #default="scope">{{  scope.row.roi>0 ?scope.row.roi+" %": "0"}}</template>
         </el-table-column>
        <el-table-column align="left" label="新用户占比" prop="rateNewByActiveUser" width="80">
            <template #default="scope">{{  scope.row.rateNewByActiveUser>0 ?scope.row.rateNewByActiveUser+" %": "0"}}</template>
         </el-table-column>
        <el-table-column align="left" label="播放人数-新用户" prop="watchUserCountByNew" width="120" />
        <el-table-column align="left" label="播放人数-全部" prop="watchUserCountByAll" width="120" />
        <el-table-column align="left" label="新用户观看率" prop="rateWatchUserNewByAllNewUser" width="80">
            <template #default="scope">{{  scope.row.rateWatchUserNewByAllNewUser>0 ?scope.row.rateWatchUserNewByAllNewUser+" %": "0"}}</template>
         </el-table-column>
        <el-table-column align="left" label="活跃用户观看率" prop="rateWatchUserActiveByAllActiveUser" width="80">
            <template #default="scope">{{  scope.row.rateWatchUserActiveByAllActiveUser>0 ?scope.row.rateWatchUserActiveByAllActiveUser+" %": "0"}}</template>
         </el-table-column>
        <el-table-column align="left" label="人均观看集数" prop="avgWatchMovieByAllWatchUser" width="120" />
        <el-table-column align="left" label="充值收入" prop="allPaySum" width="120" />
        <el-table-column align="left" label="充值人数" prop="allPayUserCount" width="120" />
        <el-table-column align="left" label="客单价" prop="customerAvgCost" width="120" />
        <el-table-column align="left" label="充值笔数" prop="allPayCount" width="120" />
        <el-table-column align="left" label="人均充值笔数" prop="customerAvgPayCount" width="120" />
        <el-table-column align="left" label="会员收入" prop="vpPay" width="120" />
        <el-table-column align="left" label="看点收入" prop="ptProductCost" width="120" />

        <!-- <el-table-column align="left" label="原价" prop="originCost" width="120">
            <template #default="scope">{{  scope.row.originCost>0 ?(scope.row.originCost/100).toFixed(2)+" 元": "0 元"}}</template>
         </el-table-column> -->

        </el-table>
        <!-- <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            />
        </div> -->
    </div>

  </div>
</template>

<script setup>

import {
  createTProduct,
  deleteTProduct,
  deleteTProductByIds,
  updateTProduct,
  findTProduct,
  getTProductList
} from '@/api/tProduct'

import {
  getStatisticsLine,
} from '@/api/dataCenter'

// 全量引入格式化工具 请按需保留
import * as echarts from 'echarts'
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox,ElLoading } from 'element-plus'
import { ref, reactive ,nextTick, onMounted, onUnmounted, shallowRef,toRefs } from 'vue'

import table2Excel from 'js-table2excel' // 引入  js-table2excel
// import * as XLSX from "xlsx" // 引入  xlsx

defineOptions({
    name: 'TProduct'
})

//引用菜单按钮权限组件
import { useBtnAuth } from '@/utils/btnAuth'
    const btnAuth = useBtnAuth()

// 自动化生成的字典（可能为空）以及字段
const platOptions = ref([])
const productBackgroundColorOptions = ref([])
const productLogoStyleOptions = ref([])
const productTypeOptions = ref([])
const productStatusOptions = ref([])
const productVipOptions = ref([])
const switchOptions = ref([])
const productVipDescOptions = ref([])

const formData = ref({

        })



// 验证规则
const rule = reactive({
               platId : [{
                   required: true,
                   message: '',
                   trigger: ['input','blur'],
               },
              ],
})

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getLineData()
  line()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getLineData()
  })
  


  // chart.value.dispose()
  // chart.value = null

  // chartRate.value.dispose()
  // chartRate.value = null

  // nextTick()
  // chart.value = echarts.init(echart.value /* 'macarons' */)
  // chartRate.value = echarts.init(echartRate.value /* 'macarons' */)
  // chart.value.clear()
  // chartRate.value.clear()
  line()

}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getLineData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getLineData()
}

// 查询
// const getTableData = async() => {
//   const table = await getTProductList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
//   if (table.code === 0) {

//   }
// }

// getTableData()

// ==============  折线控制 ==========
var lineLegendData = []
const lineDateData = ref([])
const lineGraphsDataList = ref([])

var lineRateLegendData = []
const lineRateDateData = ref([])
const lineRateGraphsDataList = ref([])

const getLineData = async() => {
  lineLegendData.length = 0;
  lineGraphsDataList.value.length = 0;

  lineRateLegendData.length = 0;
  lineRateGraphsDataList.value.length = 0;

  const line = await getStatisticsLine({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (line.code === 0) {

    tableData.value = line.data.list.list
    total.value = line.data.list.count
    page.value = line.data.list.page
    pageSize.value = line.data.list.pageSize


    lineDateData.value = line.data.list.dateList
 
    for (const k in line.data.list.lineGraphsDataDto) {
      const lineGraphsData ={
        name:line.data.list.lineGraphsDataDto[k].name,
        type:'line',
        //stack:'Total',
        data:line.data.list.lineGraphsDataDto[k].dataList,
        connectNulls: true
      }

      lineLegendData.push(lineGraphsData.name)
      lineGraphsDataList.value.push(lineGraphsData)
    
    }

    lineRateDateData.value = line.data.list.dateList
 
    for (const k in line.data.list.lineGraphsDataRateDto) {
      const lineRateGraphsData ={
        name:line.data.list.lineGraphsDataRateDto[k].name,
        type:'line',
        // stack:'Total',
        data:line.data.list.lineGraphsDataRateDto[k].dataList,
        connectNulls: true
      }

      lineRateLegendData.push(lineRateGraphsData.name)
      lineRateGraphsDataList.value.push(lineRateGraphsData)
    
    }

    

  }
}
// ============== 表格控制部分结束 ===============


const chart = shallowRef()
const echart = ref()

const chartRate = shallowRef()
const echartRate = ref()


onMounted(async() => {
  await nextTick()
   chart.value = echarts.init(echart.value /* 'macarons' */)
   chartRate.value = echarts.init(echartRate.value /* 'macarons' */)

   
   await getLineData()

   line()
})

onUnmounted(() => {
  if (!chart.value) {
    return
  }
  chart.value.dispose()
  chart.value = null


  if (!chartRate.value) {
    return
  }
  chartRate.value.dispose()
  chartRate.value = null
})

const line = async () =>  {
  chart.value.setOption( {
  title: {
    text: ''
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: lineLegendData
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: lineDateData.value
  },
  yAxis: {
    type: 'value'
  },
  series:lineGraphsDataList.value
}, true)

chartRate.value.setOption( {
  title: {
    text: ''
  },
  tooltip: {
    trigger: 'axis'
  },
  legend: {
    data: lineRateLegendData
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  toolbox: {
    feature: {
      saveAsImage: {}
    }
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: lineRateDateData.value
  },
  yAxis: {
    type: 'value'
  },
  series:lineRateGraphsDataList.value
}, true)
// chart.value.resize();
// chartRate.value.resize();
}



const state = reactive({
  exportConfig: [ // 导出Excel表格配置
    {
      title: '日期',
      key: 'createTime',
      type: 'text'
    },
    {
      title: '总新增',
      key: 'regUser',
      type: 'text'
    },
    {
      title: '投放新增',
      key: 'regUserByReferral',
      type: 'text'
    },
    {
      title: '活跃',
      key: 'regUserByActive',
      type: 'text'
    },
    {
      title: '投放消耗',
      key: 'statCost',
      type: 'text'
    },
    {
      title: 'roi %',
      key: 'roi',
      type: 'text',
    },
    {
      title: '新用户占比 %',
      key: 'rateNewByActiveUser',
      type: 'text'
    },
    {
      title: '播放人数-新用户',
      key: 'watchUserCountByNew',
      type: 'text'
    },
    {
      title: '播放人数-全部',
      key: 'watchUserCountByAll',
      type: 'text'
    },
    {
      title: '新用户观看率 %',
      key: 'rateWatchUserNewByAllNewUser',
      type: 'text'
    },
    {
      title: '活跃用户观看率 %',
      key: 'rateWatchUserActiveByAllActiveUser',
      type: 'text'
    }, 
    {
      title: '人均观看集数',
      key: 'avgWatchMovieByAllWatchUser',
      type: 'text'
    },
    {
      title: '充值收入',
      key: 'allPaySum',
      type: 'text'
    },
    {
      title: '充值人数',
      key: 'allPayUserCount',
      type: 'text'
    },
    {
      title: '客单价',
      key: 'customerAvgCost',
      type: 'text'
    },
    {
      title: '充值笔数',
      key: 'allPayCount',
      type: 'text'
    },
    {
      title: '人均充值笔数',
      key: 'customerAvgPayCount',
      type: 'text'
    },
    {
      title: '会员收入',
      key: 'vpPay',
      type: 'text'
    },
    {
      title: '看点收入',
      key: 'ptProductCost',
      type: 'text'
    },
  ]
  
})

const {exportConfig } = toRefs(state)



// 所有数据导出
const allExport = async () => {
  ElMessageBox.close() // 关闭弹出框
  const loading = ElLoading.service({ // 打开遮罩层
    lock: true,
    text: '请稍等...',
    background: 'rgba(255, 255, 255, 0.5)',
  })
    // 这里是去调后台接口，拿到需要导出的所有数据
    const res = await getStatisticsLine({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
    // if(res.data.list.length > 0){
    //   for(var i= 0; i<res.data.list.length; i++){

    //   }
    // }
    console.log(res.data.list.list)
    let list = JSON.stringify(res.data.list.list)
    list = JSON.parse(list)
    table2Excel(state.exportConfig, list, getFormatDate()+'汇总数据统计')
    loading.close() // 关闭遮罩层
}

// 获取需要的字典 可能为空 按需保留
const setOptions = async () =>{
    platOptions.value = await getDictFunc('plat')
    productBackgroundColorOptions.value = await getDictFunc('productBackgroundColor')
    productLogoStyleOptions.value = await getDictFunc('productLogoStyle')
    productTypeOptions.value = await getDictFunc('productType')
    productStatusOptions.value = await getDictFunc('productStatus')
    productVipOptions.value = await getDictFunc('productVip')
    switchOptions.value = await getDictFunc('switch')
    productVipDescOptions.value = await getDictFunc('productVipDesc')
}

// 获取需要的字典 可能为空 按需保留
setOptions()


// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
    multipleSelection.value = val
}


// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')
// 控制vip表单元素展示
let fromRadioTypeVIP = ref(false)
// 控制看点+赠点表单元素展示
let fromInputTypeYUEBI = ref(false)

const getFormatDate =  () => {
    var date = new Date();
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
        month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
        strDate = "0" + strDate;
    }
    var currentDate = date.getFullYear() + "-" + month + "-" + strDate
            + " " + date.getHours() + ":" + date.getMinutes() + ":" + date.getSeconds();
    return currentDate;
}







</script>

<style lang="scss" scoped>
    .gva-card-box{
      @apply p-4;
      &+.gva-card-box{
        @apply pt-0;
      }
    }
.dashboard-line-box {
  margin-top: 5px;
  .dashboard-line {
    background-color: #fff;
    height: 400px;
    width: 100%;
  }
  .dashboard-line-title {
    font-weight: 600;
    margin-bottom: 12px;
  }
}
</style>
